package com.jk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jk.model.*;
import com.jk.service.WJSService;
import com.jk.utils.OSSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("wjs")
public class WJSController {

    @Reference(check = false,timeout = 100000)
    private WJSService wjsService;

    @Autowired
    private MongoTemplate mongoTemplate;

    //新增mogodb
    @RequestMapping("findSaveProduct")
    @ResponseBody
    public Map saveproduct(Integer productId,HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        if (attribute == null){
            result.put("code",1);
            result.put("msg","请登录");
            return result;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String dateString = formatter.format(date);
        MogoBean mogoBean = new MogoBean();
        mogoBean.setCreateTime(dateString);
        mogoBean.setProductId(productId);
        mogoBean.setUserId(attribute.getId());
        result.put("code",0);
        result.put("msg","加入成功");
        mongoTemplate.save(mogoBean);
        return result;
    }

    //查询mogodb
    @RequestMapping("findmogodb")
    @ResponseBody
    public Map findmogodb(/*Integer page, Integer rows,*/ MogoBean mogoBean,HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean user = (UserBean) session.getAttribute(session.getId());
        Integer id = user.getId();
        Query query = new Query();
        //查询count
        long count = mongoTemplate.count(query , MogoBean.class);
        result.put("total", count);
        //排序
        query.with(new Sort(Sort.Direction.DESC,"createTime"));
        /*//设置分页
        query.skip((page-1)*rows);
        query.limit(rows);*/
        query.addCriteria(Criteria.where("userId").is(id));
        List<MogoBean> mogoBeans = mongoTemplate.find(query, MogoBean.class);
        ArrayList<ProductBean> list = new ArrayList<>();
        for (MogoBean bean : mogoBeans) {
            ProductBean productBean = wjsService.queryProductByProductId(bean.getProductId());
                productBean.setProductDeliveryTime(bean.getCreateTime());
            list.add(productBean);
        }
        result.put("rows",list);
        return result;
    }

    /**
     * 新增店铺
     */
    @RequestMapping("saveStore")
    @ResponseBody
    public Map saveStore(StoreBean storeBean,HttpServletRequest request) {
        System.out.println("新增店铺");
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean userBean = (UserBean) session.getAttribute(session.getId());
        if (userBean == null){
            result.put("code",1);
            result.put("msg","必须先成为用户");
            return result;
        }
        Integer id = userBean.getId();
        UserBean user = wjsService.queryUserInfoById(id);
        if (user != null){
            result.put("code",2);
            result.put("msg","你已经是商家了");
            return result;
        }
        wjsService.saveStore(storeBean);
        StoreBean storeBean1 = wjsService.findStoreName(storeBean.getStoreName());
        Integer id1 = storeBean1.getId();
        System.out.println(id1);
        wjsService.saveUserStoreId(id,id1);
        result.put("code",0);
        result.put("msg","申请中，请耐心等候");
        return result;
    }

    //已卖出的商品查询
    @RequestMapping("findUserList")
    @ResponseBody
    public Map findUserList(Integer page, Integer rows, UserBean userBean, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        Map userList = wjsService.findUserList(page, rows, userBean, id);
        return userList;
    }
    //商品加载
    @RequestMapping("shangpin")
    @ResponseBody
    public List<ProductBean> shangpin(){
        return wjsService.shangpin();
    }

    //买家查询
    @RequestMapping("yimai")
    @ResponseBody
    public Map yimai(Integer page, Integer rows, UserBean userBean, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        Map yimai = wjsService.yimai(page, rows, userBean, id);
        return yimai;
    }

    //待付款
    @RequestMapping("daifukuan")
    @ResponseBody
    public Map daifukuan(Integer page, Integer rows, UserBean userBean, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        Map daifukuan = wjsService.daifukuan(page, rows, userBean, id);
        return daifukuan;
    }

    //待发货
    @RequestMapping("daifahuo")
    @ResponseBody
    public Map daifahuo(Integer page, Integer rows, UserBean userBean, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        Map daifahuo = wjsService.daifahuo(page, rows, userBean, id);
        return daifahuo;
    }

    //注册
    @RequestMapping("register")
    @ResponseBody
    public String register(UserBean userBean, HttpSession session) {
        //判断用户名是否重复
        UserBean queryUser = wjsService.queryUser(userBean);
        if (queryUser != null) {
            return "用户已存在";
        } else {
            wjsService.register(userBean);
            session.setAttribute("user", userBean);
            return "注册成功";
        }
    }

    //购买过的店铺
    @RequestMapping("shangdian")
    @ResponseBody
    public Map shangdian(Integer page, Integer rows, UserBean userBean, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        Map shangdian = wjsService.shangdian(page, rows, userBean, id);
        return shangdian;
    }

    //买家查询树
    @RequestMapping("findMaiList")
    @ResponseBody
    public List<MaiTree> findMaiList(){
        List<MaiTree> manageTree = wjsService.findMaiList();
        return manageTree;
    }

    //个人信息
    @RequestMapping("findgeren")
    @ResponseBody
    public Map findgeren(Integer page, Integer rows, UserBean userBean,HttpServletRequest request) {
        HttpSession session = request.getSession();
        UserBean UserBean = (UserBean) session.getAttribute(session.getId());
        Integer id = UserBean.getId();
        Map findgeren = wjsService.findgeren(page, rows, userBean, id);
        return findgeren;
    }
    //收货地址
    @RequestMapping("dizi")
    @ResponseBody
    public Map dizi(Integer page, Integer rows, UserAcceptsite userAcceptsite,HttpServletRequest request){
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        Map dizi = wjsService.dizi(page, rows, userAcceptsite, id);
        return dizi;
    }

    //跳转页面(注销)
    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute(session.getId());
        return "login";
    }

    //修改密码
    @RequestMapping("updatePassword")
    @ResponseBody
    public void updatePassword(String password, Integer userId) {
        wjsService.updatePassword(password,userId);
    }
    //验证密码
    @RequestMapping("codePassword")
    @ResponseBody
    public Map codePassword(String userPassword, HttpSession session) {
        return wjsService.codePassword(userPassword,session);
    }

    /**
     * 图片上传
     * @param imgfile
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("upload")
    @ResponseBody
    public Map upload(MultipartFile imgfile, HttpServletRequest request) throws IOException {
        OSSClientUtil ossClient = new OSSClientUtil();
        String name = ossClient.uploadImg2Oss(imgfile);
        String fileUpload = ossClient.getImgUrl(name);
        HashMap<String, Object> result = new HashMap<>();
        result.put("img", fileUpload);
        return result;
    }

    //个人信息修改
    @RequestMapping("updateuser")
    @ResponseBody
    public Boolean updateuser(UserBean userBean) {
        try {
            if (userBean.getId() != null){
                wjsService.updateuser(userBean);
            }else{
                wjsService.saveUser(userBean);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //个人信息回显
    @RequestMapping("findUser")
    @ResponseBody
    public UserBean findUser(Integer id) {
        return wjsService.findUser(id);
    }
    /**
     * 查询所有购买过的商品 订单
     * @param page
     * @param rows
     * @param orderBean
     * @return
     */
    @RequestMapping("findOrderList")
    @ResponseBody
    public Map findOrderList(Integer page, Integer rows, OrderBean orderBean){
        return wjsService.findOrderList(page,rows,orderBean);
    }

    //新增评论
    @RequestMapping("addlun")
    @ResponseBody
    public Map addlun(Integer productId, PinlunBean pinlunBean ,HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String dateString = formatter.format(date);
        pinlunBean.setCreateTime(dateString);
        pinlunBean.setProductId(productId);
        pinlunBean.setUserId(attribute.getId());

        result.put("code",0);
        result.put("msg","加入成功");
        mongoTemplate.save(pinlunBean);
        wjsService.updatetai(productId);
        return result;
    }

    /**
     * 查询所有订单
     * @param page
     * @param rows
     * @param orderBean
     * @param request
     * @return
     */
    @RequestMapping("findOrder")
    @ResponseBody
    public Map findOrder(Integer page, Integer rows, OrderBean orderBean,HttpServletRequest request){
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        return wjsService.findOrder(page, rows, orderBean,attribute.getId());
    }

    /**
     * 待评价的订单
     * @param page
     * @param rows
     * @param orderBean
     * @param request
     * @return
     */
    @RequestMapping("pingjiafindOrder")
    @ResponseBody
    public Map pingjiafindOrder(Integer page, Integer rows, OrderBean orderBean,HttpServletRequest request){
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        return wjsService.pingjiafindOrder(page, rows, orderBean,attribute.getId());
    }

    /*@RequestMapping("findlun")
    @ResponseBody
    public Map findlun(Integer page, Integer rows,PinlunBean pinlunBean,HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean user = (UserBean) session.getAttribute(session.getId());
        Integer id = user.getId();
        Query query = new Query();
        //查询count
        long count = mongoTemplate.count(query , PinlunBean.class);
        result.put("total", count);
        //排序
        query.with(new Sort(Sort.Direction.DESC,"createTime"));
        //设置分页
        query.skip((page-1)*rows);
        query.limit(rows);
        query.addCriteria(Criteria.where("userId").is(id));
        List<PinlunBean> pinlunBeans = mongoTemplate.find(query, PinlunBean.class);
        ArrayList<ProductBean> list = new ArrayList<>();
        for (PinlunBean bean : pinlunBeans) {
            ProductBean productBean = wjsService.queryProductId(bean.getProductId());
            productBean.setProductDeliveryTime(bean.getCreateTime());
            list.add(productBean);
        }
        result.put("rows",list);
        return result;
    }*/
    //查询用户评价
    @RequestMapping("findlun")
    @ResponseBody
    public Map findlun(Integer page, Integer rows,PinlunBean pinlunBean,HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean user = (UserBean) session.getAttribute(session.getId());
        Integer id = user.getId();
        Query query = new Query();
        //查询count
        long count = mongoTemplate.count(query , PinlunBean.class);
        result.put("total", count);
        //排序
        query.with(new Sort(Sort.Direction.DESC,"createTime"));
        //设置分页
        query.skip((page-1)*rows);
        query.limit(rows);
        query.addCriteria(Criteria.where("userId").is(id));
        List<PinlunBean> pinlunBeans = mongoTemplate.find(query, PinlunBean.class);
        ArrayList<ProductBean> list = new ArrayList<>();
        for (PinlunBean bean : pinlunBeans) {
            ProductBean productBean = wjsService.queryProductId(bean.getProductId());
            productBean.setProductDeliveryTime(bean.getCreateTime());
            list.add(productBean);
        }
        result.put("rows",list);
        return result;
    }

}